var express = require('express');
var router = express.Router();


const Query=require('../utils/db.js')

const { api_url }=require('../utils/config.js')

const timestamp=require('time-stamp')

const path=require('path')
const fs=require('fs')
const formidable=require('formidable')

const {v4:uuid}=require('uuid')

 router.use((req, res, next) => {

    // console.log( req.headers )
    //let tokenStr = 'adflkajfd;lajfd;kajfd;lkjsa;fdlkjsa;lfdkjsa;dlfksa;lfdk'
    // req.headers.authorization
  
    // console.log( verifyToken( tokenStr ) )
    // if( !verifyToken( req.headers.authorization ) ){//如果取反为真，则代表token是无效
    //   next({msg:'token无效，请登录'})
    //   return
    // }
  
    next()
    // console.log('个人中心的')
  })
  


//根据视频id获取视频的播放地址
router.get('/video',async (req,res,next)=>{
    
         //先验证token是否有效（判断你是否登录了）
           //    let s =  verifyToken( 'adfasfdlkjsafdsajfdlsafdk' )
           // let token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.    eyJ1c2VybmFtZSI6ImFhYWEiLCJpYXQiOjE2MjM4MjgwODMsImV4cCI6MTYyMzkxNDQ4M30.     5ynHnInIumzOAN_dds7EzsCu5Lv2nQchlvV5kJfJDlI'
           // let token = req.headers.authorization
        //    if(  !verifyToken( token ) ){
        //       next({
        //           msg:'请传递token',
        //           status:500
        //       })
        //       return
        //    }




    // res.send('获取视频')
    let { id = '' } = req.query
    if (id == '') {
        next({
            msg: '请传递必要参数',
            status: 500
        })
        return
    }
    let sql = `SELECT video_title, CONCAT('${api_url}','/uploads/videos/',video_src) AS video_src, cid FROM e_video WHERE id=${id}`
    let res1 = await Query(sql)
    // res.send(res1)
    //这里需要判断res1.result的长度是否大于0，如果不大于则代表传的参数不对
    let data = {
        msg: "OK",
        status: 200,
        result: res1.result[0],
       
    }
    res.send(data)
})


//报名
router.post('/study',async (req,res,next)=>{
   
     let {cid='',mid=''}=req.body

     if(cid==''|| mid==''){
         next({
             msg:'请传递必要参数',
             status:500
         })
         return
     }


     //判断此用户有无报名此课程
     let sql2 = `SELECT * FROM e_order WHERE cid = '${cid}' AND mid = '${mid}'`

     let res2=await Query(sql2)
     if(res2.result.length>0){
          next({
              msg:'已经报名',
              status:500
          })
          return
     }

     let random6=(Math.random()+'').substring(2,8)
     let oid=timestamp('YYYYMMDDHHmmss')+random6     //年月日时分秒 + 6位随机数
     let createdate=Date.now()
     let sql1 = `INSERT INTO e_order ( oid,cid,mid,createdate,status ) VALUES ( '${oid}','${cid}','${mid}',${createdate},1 )`
     let res1=await Query(sql1)

     if(res1.result.affectedRows>0){
         next({
             msg:'ok',
             status:200
         })
     }
})



//更新头像
router.post('/uploadhead',async (req,res,next)=>{
     
      const form=formidable({
          uploadDir:path.join(__dirname,'../tempdir'),
      })
   

      form.parse(req, async (err,fields,files)=>{
       
        if(fields.mid==''){
            next({
                msg:'请传递正确的用户id',
                status:500
            })
            return
         }
   
          let sourcePath=files.f.path
          let newname=uuid()+path.extname(files.f.name)
          let newPath=path.join(__dirname,'../uploads/head',newname)
          fs.renameSync(sourcePath,newPath)


          let sql = `UPDATE e_member SET head_photo_url='${newname}' WHERE mid='${fields.mid}'`
          let res1=await Query(sql)

          let data={
            msg:'ok',
            status:200,
            result:`${api_url}/uploads/head/${newname}`
          }
          res.send(data)
      })
})


//获取用户
router.get('/user',async (req,res,next)=>{
    let { mid = '' } = req.query
    if (mid == '') {
        next({
            msg: '查无此人',
            status: 500
        })
        return
    }

    let sql=`SELECT id, mid, realname, username, sex, birthdate, city, CONCAT('${api_url}','/uploads/head/',head_photo_url) AS head_photo_url,createdate FROM e_member WHERE mid='${mid}'`

    
    let res1 = await Query(sql)
   
    let data = {
        msg: "OK",
        status: 200,
        result: res1.result[0]
    }
    res.send(data)
})


//更新用户
router.put('/user',async (req,res,next)=>{
    let { realname = '', sex = '',birthdate = '', city = '',mid = ''  } = req.body
    if (realname == ''|| sex == ''||birthdate == ''|| city == ''||mid == '' ) {
        next({
            msg: '请传递必要参数',
            status: 800
        })
        return
    }

    let sql = `UPDATE e_member SET realname='${realname}',sex='${sex}',birthdate='${birthdate}',city='${city}' WHERE mid='${mid}'`

    
    let res1 = await Query(sql)
   
    let data = {
        msg: "OK",
        status: 200,
    }
    res.send(data)
})


//获取学习记录
router.get('/orders',async (req,res,next)=>{
    let {mid='',oid='',title='',price='',subject_name='',area_name='',createdate=''} = req.query
    if (mid =='') {
        next({
            msg: '请传递必要参数',
            status: 500
        })
        return
    }

    let sql1=`SELECT oid,title,price,subject_name,area_name,createdate,CONCAT('${api_url}','/uploads/courses/',image_src) AS image_src FROM e_order JOIN e_course ON e_order.cid=e_course.cid WHERE mid='${mid}'`
    let res1 = await Query(sql1)

    let data = {
        msg: "OK",
        status: 200,
        result: res1.result
    }
    res.send(data)
   


    
})

module.exports = router;